package com.order.distribute.listen;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.order.distribute.mapper.DistributeMapper;
import com.order.distribute.pojo.Distribute;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 分单
 * @Author 徐成
 * @Date 2019/12/17 16:06
 * @Version 1.0
 */
@Component
@Slf4j
public class DistributeReceiverConsumer {

    @Autowired
    private DistributeMapper distributeMapper;
    /**
     * 分单队列
     */
    public static final String QUEUE_NAME_TRANSACTION = "xucheng.distribute.queue";
    @Bean
    public Queue scoreQueue() {
        return new Queue(QUEUE_NAME_TRANSACTION, true);
    }
    @RabbitListener(queues = QUEUE_NAME_TRANSACTION)
    public void orderReceiver(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception{
        try {
            
            String msgBody = new String(message.getBody(), "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(msgBody);
            String orderNo = jsonObject.getString("orderNo");
            //幂等处理
            QueryWrapper<Distribute> wrapper = new QueryWrapper<>();
            Map hashMap = new HashMap();
            hashMap.put("order_no", orderNo);
            wrapper.allEq(hashMap);
            Distribute distribute = distributeMapper.selectOne(wrapper);
            if (distribute != null) {
                //丢弃消息
                log.info("订单已存在，告诉MQ 重复消息放弃接受");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            }
            //处理分单，成功则签收消息
            distribute = new Distribute();
             distribute.setOrderNo(orderNo);
             distribute.initDistribute();
            Boolean isInsertSuccess = distributeMapper.insert(distribute) == 1L;
            if (isInsertSuccess) {
                //手动签收消息，通知MQ 删除此消息
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                log.info("成功接收。。。");
            }
        } catch (Exception e) {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
				log.info("-------出错了");
				//e.printStackTrace();
        }
    }
}
